package com.um.psystem.service.mtService.impl;

import cn.hutool.core.util.StrUtil;
import com.um.psystem.entity.ExcelHeader;
import com.um.psystem.enums.ResponseEnum;
import com.um.psystem.mapper.platform.PublicMapper;
import com.um.psystem.model.vo.JsonResult;
import com.um.psystem.service.mtService.IAssetsMonthlyService;
import com.um.psystem.utils.EasyExcelUtils;
import com.um.psystem.utils.RTX;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: qy
 * @Date: 2021/1/9 - 14:04
 * @Description: 月度申请实现类
 * @version: 1.0
 */
@Service
public class AssetsMonthlyService implements IAssetsMonthlyService {
    @Autowired
    PublicMapper publicMapper;

    @Override
    public List<Map<String, Object>> getMonCategoryList(Map map) {
        Map paramsMap = new HashMap();
        Integer page = Integer.parseInt((map.get("page") != null ? map.get("page").toString() : "0"));
        Integer rows = Integer.parseInt((map.get("rows") != null ? map.get("rows").toString() : "0"));
        String sql = " select count(*) as totals from ws_eng_assets_monthly_info ";
        System.out.println("sql1:" + sql);
        paramsMap.put("sqlStr", sql);
        int totals = 0;
        List<Map<String, Object>> list_count = publicMapper.getPublicItems(paramsMap);
        if (list_count.size() > 0) {
            totals = Integer.parseInt(list_count.get(0).get("totals").toString());
        }
        sql = " select a.*," + totals + " as totals from ws_eng_assets_monthly_info a order by mon_category_id desc";
        if (page != 0 && rows != 0) {
            sql += " limit #{startIndex},#{rows} ";
            paramsMap.put("startIndex", (page - 1) * rows);
            paramsMap.put("rows", rows);
        }
        paramsMap.put("sqlStr", sql);
        return publicMapper.getPublicItems(paramsMap);
    }

    @Override
    public List<Map<String, Object>> getMonCategoryInfo(Map map) {
        return null;
    }

    @Override
    public void exportMonthlyApplyData(HttpServletResponse response, Map map) {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码
        String fileName = null;
        try {
            fileName = URLEncoder.encode(map.get("mon_date")+ "_" + map.get("operator") + "月度辅料申请清单", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        List<ExcelHeader> headerList = new ArrayList<>();
        if(map.get("mon_category_id").equals("1")) {
            headerList.add(new ExcelHeader("rownum", "序号"));
            headerList.add(new ExcelHeader("type_dtl_no", "编号"));
            headerList.add(new ExcelHeader("type_dtl_name", "名称"));
            headerList.add(new ExcelHeader("sizes", "规格型号"));
            headerList.add(new ExcelHeader("operator", "需求人"));
            headerList.add(new ExcelHeader("stockin_num", "仓库库存"));
            headerList.add(new ExcelHeader("apply_num", "月需求数量"));
            headerList.add(new ExcelHeader("apply_type", "申购类别"));
            headerList.add(new ExcelHeader("unit", "单位"));
            headerList.add(new ExcelHeader("apply_reason", "申请原因描述"));
            headerList.add(new ExcelHeader("check_state", "已确认完毕"));
            headerList.add(new ExcelHeader("remark", "备注"));
        }else if(map.get("mon_category_id").equals("2")){
            headerList.add(new ExcelHeader("rownum", "序号"));
            headerList.add(new ExcelHeader("type_dtl_no", "物料代码"));
            headerList.add(new ExcelHeader("type_dtl_name", "名称"));
            headerList.add(new ExcelHeader("sizes", "规格型号"));
            headerList.add(new ExcelHeader("apply_num", "月需求数量"));
            headerList.add(new ExcelHeader("unit", "单位"));
            headerList.add(new ExcelHeader("apply_reason", "申请原因"));
            headerList.add(new ExcelHeader("operator", "申请人"));
            headerList.add(new ExcelHeader("remark", "备注"));
            headerList.add(new ExcelHeader("check_state", "已确认完毕"));
        }else if(map.get("mon_category_id").equals("3")){
            headerList.add(new ExcelHeader("rownum", "序号"));
            headerList.add(new ExcelHeader("type_dtl_no", "物料编号"));
            headerList.add(new ExcelHeader("type_dtl_name", "名称"));
            headerList.add(new ExcelHeader("sizes", "规格型号"));
            headerList.add(new ExcelHeader("apply_num", "月需求数量"));
            headerList.add(new ExcelHeader("unit", "单位"));
            headerList.add(new ExcelHeader("apply_type", "申购类别"));
            headerList.add(new ExcelHeader("operator", "申请人"));
            headerList.add(new ExcelHeader("check_state", "已确认完毕"));
            headerList.add(new ExcelHeader("remark", "备注"));
        }

        List<Map<String, Object>> dataList = getMonApplyInfoList(map);
        OutputStream excelOutputStream = EasyExcelUtils.exportDataToExcel(headerList, dataList);
        try {
            response.getOutputStream().write(((ByteArrayOutputStream) excelOutputStream).toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Map<String, Object>> getMonApplyInfoList(Map map) {
        Map paramsMap = new HashMap();
        String sqltmp = "";
        String type_dtl_no = "";
        String type_dtl_name = "";
        String sizes = "";
        String mon_date = "";
        String operator = "";
        String mon_category_id = "";
        if (StrUtil.isNotBlank(map.get("type_dtl_no") != null ? map.get("type_dtl_no").toString() : null)) {
            sqltmp += " and c.type_dtl_no=#{type_dtl_no}";
            type_dtl_no = map.get("type_dtl_no").toString();
            paramsMap.put("type_dtl_no", type_dtl_no);
        }
        if (StrUtil.isNotBlank(map.get("type_dtl_name") != null ? map.get("type_dtl_name").toString() : null)) {
            sqltmp += " and c.type_dtl_name like #{type_dtl_name}";
            type_dtl_name = map.get("type_dtl_name").toString();
            paramsMap.put("type_dtl_name", "%"+type_dtl_name+"%");
        }
        if (StrUtil.isNotBlank(map.get("sizes") != null ? map.get("sizes").toString() : null)) {
            sqltmp += " and c.sizes like #{sizes}";
            sizes = map.get("sizes").toString();
            paramsMap.put("sizes", "%" + sizes + "%");
        }
        if (StrUtil.isNotBlank(map.get("operator") != null ? map.get("operator").toString() : null)) {
            sqltmp += " and a.operator=#{operator}";
            operator = map.get("operator").toString();
            paramsMap.put("operator", operator);
        }
        mon_category_id = map.get("mon_category_id").toString();
        mon_date = map.get("mon_date").toString();
        Integer page = Integer.parseInt((map.get("page") != null ? map.get("page").toString() : "0"));
        Integer rows = Integer.parseInt((map.get("rows") != null ? map.get("rows").toString() : "0"));
        String sql = " select count(*) as totals from ws_eng_assets_monthly_info_dtl a " +
                "join ws_eng_assets_monthly_info b on a.mon_category_id=b.mon_category_id " +
                "join ws_eng_assets_type_dtl c on a.type_dtl_id=c.type_dtl_id " +
                "join ws_eng_assets_type_main d on c.type_main_id=d.type_main_id " +
                "where  a.mon_date=#{mon_date} and " +
                " a.mon_category_id=#{mon_category_id} " + sqltmp + " group by a.mon_dtl_id ";
        paramsMap.put("sqlStr", sql);
        paramsMap.put("mon_date", mon_date);
        paramsMap.put("operator", operator);
        paramsMap.put("mon_category_id", mon_category_id);
        int totals = 0;
        List<Map<String, Object>> list_count = publicMapper.getPublicItems(paramsMap);
        if (list_count.size() > 0) {
            totals = Integer.parseInt(list_count.get(0).get("totals").toString());
        }
        sql = "select c.type_dtl_no,c.k3_code,c.type_dtl_name,c.sizes,a.apply_num,a.applied_num," +
                "a.stockin_num,a.apply_type,c.unit,a.apply_reason,a.check_flag,if(a.check_flag='999','已确认','未确认') as check_state," +
                "a.mon_dtl_id,a.operator,c.type_dtl_id," +
                "a.mon_date,a.remark,@rownum:=@rownum+1 as rownum " +
                "," + totals + " as totals " +
                "from  ws_eng_assets_monthly_info_dtl a  join (select @rownum:=0) r " +
                "join ws_eng_assets_monthly_info b on a.mon_category_id=b.mon_category_id " +
                "join ws_eng_assets_type_dtl c on a.type_dtl_id=c.type_dtl_id " +
                "join ws_eng_assets_type_main d on c.type_main_id=d.type_main_id " +
                "where a.mon_date=#{mon_date} and " +
                "a.mon_category_id=#{mon_category_id} " +
                "and a.type_dtl_id is not null " + sqltmp + " group by a.mon_dtl_id " +
                "union all " +
                "select '' as type_dtl_no,'' as k3_code,'' as type_dtl_name,'' as sizes,a.apply_num,a.applied_num," +
                "a.stockin_num,a.apply_type,'' as unit,a.apply_reason,a.check_flag,if(a.check_flag='999','已确认','未确认') as check_state," +
                "a.mon_dtl_id,a.operator,'' as type_dtl_id," +
                "a.mon_date,a.remark,@rownum:=@rownum+1 as rownum " +
                "," + totals + " as totals " +
                "from ws_eng_assets_monthly_info_dtl a  join (select @rownum:=0) r " +
                "join ws_eng_assets_monthly_info b on a.mon_category_id=b.mon_category_id " +
//                "join ws_eng_assets_type_dtl c on a.type_dtl_id=c.type_dtl_id " +
//                "join ws_eng_assets_type_main d on c.type_main_id=d.type_main_id " +
                "where a.mon_date=#{mon_date} and " +
                "a.mon_category_id=#{mon_category_id} " +
                "and a.type_dtl_id is null " + sqltmp + " group by a.mon_dtl_id ";

        if (page != 0 && rows != 0) {
            sql += " limit #{startIndex},#{rows} ";
            paramsMap.put("startIndex", (page - 1) * rows);
            paramsMap.put("rows", rows);
        }
        paramsMap.put("sqlStr", sql);
        return publicMapper.getPublicItems(paramsMap);
    }

    @Override
    public List<Map<String, Object>> getStockinNumAndAppliedNum(Map map) {
        Map paramsMap = new HashMap();
        String type_dtl_no = "";
        String sql = "select stockin_num from ws_eng_assets_delivery_record " +
                "where assets_id = " +
                "(select type_dtl_id from ws_eng_assets_type_dtl where type_dtl_no = #{type_dtl_no})" +
                " order by id desc limit 1";
        if (map != null) {
            if (StrUtil.isNotBlank(map.get("type_dtl_no") != null ? map.get("type_dtl_no").toString() : null)) {
                type_dtl_no = map.get("type_dtl_no").toString();
                paramsMap.put("type_dtl_no", type_dtl_no);
            }
        }

        paramsMap.put("sqlStr", sql);
        List<Map<String, Object>> listInfo_stockinNum = publicMapper.getPublicItems(paramsMap);
        if (listInfo_stockinNum.size() == 0) {
            sql = "select sum(num) as stockin_num from ws_eng_assets_stockin_record a " +
                    "join ws_eng_assets_type_dtl b on a.type_dtl_id=b.type_dtl_id " +
                    "where b.type_dtl_no=#{type_dtl_no}";
            paramsMap.put("sqlStr", sql);
            listInfo_stockinNum = publicMapper.getPublicItems(paramsMap);
        }
//        sql = "select sum(apply_num) as applied_num from ws_eng_assets_monthly_info_dtl " +
//                "where type_dtl_id=#{type_dtl_id} and mon_date=(select mon_date from ws_eng_assets_monthly_info_dtl where mon_dtl_id=#{mon_dtl_id}) " +
//                "and operator<>(select operator from ws_eng_assets_monthly_info_dtl where mon_dtl_id=#{mon_dtl_id})";
        sql = "select sum(apply_num) as applied_num from ws_eng_assets_monthly_info_dtl " +
                "where type_dtl_id=#{type_dtl_id} and mon_date=(select mon_date from ws_eng_assets_monthly_info_dtl where mon_dtl_id=#{mon_dtl_id}) " +
                "and mon_dtl_id<>#{mon_dtl_id}";
        paramsMap.put("sqlStr", sql);
        paramsMap.put("type_dtl_id", map.get("type_dtl_id").toString());
        paramsMap.put("mon_dtl_id", map.get("mon_dtl_id").toString());
        List<Map<String, Object>> listInfo_appliedNum = publicMapper.getPublicItems(paramsMap);
        listInfo_stockinNum.addAll(listInfo_appliedNum);
        return listInfo_stockinNum;
    }

    @Override
    public JsonResult<Integer> updateMonCategory(Map map) {
        return null;
    }

    @Override
    public JsonResult<Integer> update_monApplyInfo(Map map) {
        Map paramsMap = new HashMap();
        String sql = "update ws_eng_assets_monthly_info_dtl set apply_num=#{apply_num},apply_type=#{apply_type}," +
                "apply_reason=#{apply_reason},remark=#{remark},operator_time=now() where mon_dtl_id=#{mon_dtl_id}";
        paramsMap.put("usqlStr", sql);
        paramsMap.put("apply_num", map.get("apply_num").toString());
        paramsMap.put("apply_type", map.get("apply_type").toString());
        paramsMap.put("apply_reason", map.get("apply_reason").toString());
        paramsMap.put("remark", map.get("remark").toString());
        paramsMap.put("mon_dtl_id", map.get("mon_dtl_id").toString());
        return JsonResult.success(publicMapper.updateItems(paramsMap));
    }

    @Override
    public JsonResult<Integer> submitMonthlyApply(Map map) {
        Map paramsMap = new HashMap();
        String sql = "update ws_eng_assets_monthly_info_dtl set check_flag='1' " +
                "where mon_category_id=#{mon_category_id} and mon_date=#{mon_date} and operator=#{operator}";
        paramsMap.put("usqlStr", sql);
        String apply_man = map.get("operator").toString();
        paramsMap.put("operator", apply_man);
        paramsMap.put("mon_category_id", map.get("mon_category_id").toString());
        paramsMap.put("mon_date", map.get("mon_date").toString());
        Integer updateNum = publicMapper.updateItems(paramsMap);
        if (updateNum > 0) {
            RTX.sendMsg("月度申请消息", apply_man + "已提交申请单", "石朋辉");
            return JsonResult.success(updateNum);
        } else {
            return JsonResult.error(ResponseEnum.SERVER_ERROR);
        }
    }

    @Override
    public JsonResult<Integer> checkMonthlyApply(Map map) {
        Map paramsMap = new HashMap();
        String sql = "update ws_eng_assets_monthly_info_dtl set check_flag='999'," +
                "check_man=#{check_man},check_time=now() " +
                "where mon_category_id=#{mon_category_id} and mon_date=#{mon_date} and operator=#{operator}";
        paramsMap.put("usqlStr", sql);
        paramsMap.put("check_man", map.get("check_man").toString());
        paramsMap.put("operator", map.get("operator").toString());
        paramsMap.put("mon_category_id", map.get("mon_category_id").toString());
        paramsMap.put("mon_date", map.get("mon_date").toString());
        Integer updateNum = publicMapper.updateItems(paramsMap);
        if (updateNum > 0) {
            RTX.sendMsg("月度申请消息", map.get("check_man").toString() + "已审核申请单", "黄晓婷");
            return JsonResult.success(updateNum);
        } else {
            return JsonResult.error(ResponseEnum.SERVER_ERROR);
        }
    }

    @Override
    public JsonResult<Integer> backMonthlyApply(Map map) {
        Map paramsMap = new HashMap();
        String sql = "update ws_eng_assets_monthly_info_dtl set check_flag='-1'," +
                "check_man=#{check_man},check_time=now() " +
                "where mon_category_id=#{mon_category_id} and mon_date=#{mon_date} and operator=#{operator}";
        paramsMap.put("usqlStr", sql);
        paramsMap.put("check_man", map.get("check_man").toString());
        paramsMap.put("operator", map.get("operator").toString());
        paramsMap.put("mon_category_id", map.get("mon_category_id").toString());
        paramsMap.put("mon_date", map.get("mon_date").toString());
        Integer updateNum = publicMapper.updateItems(paramsMap);
        if (updateNum > 0) {
            RTX.sendMsg("月度申请消息", map.get("check_man").toString() + "已打回申请单，打回原因："
                    + map.get("back_rs").toString(), map.get("operator").toString());
            return JsonResult.success(updateNum);
        } else {
            return JsonResult.error(ResponseEnum.SERVER_ERROR);
        }
    }

    @Override
    public JsonResult<Integer> saveMonApply_null(Map map) {
        Map paramsMap = new HashMap();
        String mon_category_id = "";
        String mon_date = "";
        String operator = "";
        mon_category_id = map.get("mon_category_id").toString();
        mon_date = map.get("mon_date").toString();
        operator = map.get("operator").toString();
        String sql = "insert into ws_eng_assets_monthly_info_dtl (mon_dtl_id,mon_category_id,mon_date,operator,check_flag) " +
                "select null,#{mon_category_id},#{mon_date},#{operator},'0' ";
        paramsMap.put("isqlStr", sql);
        paramsMap.put("mon_category_id", mon_category_id);
        paramsMap.put("mon_date", mon_date);
        paramsMap.put("operator", operator);
        int saveNum = publicMapper.saveItems(paramsMap);
        if (saveNum == 1) {
            return JsonResult.success(saveNum);
        } else {
            return JsonResult.error(400, "订单表新增失败");
        }
    }

    @Override
    public JsonResult<Integer> addMonCategory(Map map) {
        Map paramsMap = new HashMap();
        String sql = "INSERT INTO ws_eng_assets_monthly_info" +
                " VALUES" +
                " (null, #{content_description}, #{dept_group}, #{floor_workshop}, #{completed_by}," +
                " now())";
        paramsMap.put("isqlStr", sql);
        paramsMap.put("content_description", map.get("contentDes"));
        paramsMap.put("dept_group", map.get("departGroup"));
        paramsMap.put("floor_workshop", map.get("floorWorkshop"));
        paramsMap.put("completed_by", map.get("completedBy"));
        return JsonResult.success(publicMapper.saveItems(paramsMap));
    }

    @Override
    public JsonResult<Integer> addmonAssetsInfo(Map map) {
        Map paramsMap = new HashMap();
        String sql = "update ws_eng_assets_monthly_info_dtl set type_dtl_id=#{type_dtl_id},stockin_num=#{stockin_num}," +
                "applied_num=#{applied_num},operator_time=now() " +
                "where mon_dtl_id=#{mon_dtl_id}";
        paramsMap.put("usqlStr", sql);
        paramsMap.put("type_dtl_id", map.get("type_dtl_id").toString());
        paramsMap.put("mon_dtl_id", map.get("mon_dtl_id").toString());
        paramsMap.put("stockin_num", map.get("stockin_num").toString());
        paramsMap.put("applied_num", map.get("applied_num").toString());
        return JsonResult.success(publicMapper.updateItems(paramsMap));
    }

    @Override
    public JsonResult<Integer> deleMonCategory(Integer id) {
        return null;
    }

    @Override
    public JsonResult<Integer> del_monApply(Map map) {
        Map paramsMap = new HashMap();
        String sql = "delete from ws_eng_assets_monthly_info_dtl where mon_dtl_id=#{mon_dtl_id}";
        paramsMap.put("dsqlStr", sql);
        paramsMap.put("mon_dtl_id", map.get("mon_dtl_id").toString());
        return JsonResult.success(publicMapper.delItems(paramsMap));
    }

    @Override
    public JsonResult<Integer> importMonthlyApplyData(Map map) {
        Map paramsMap = new HashMap();
        String sql = "insert into ws_eng_assets_monthly_info_dtl (mon_category_id,type_dtl_id," +
                "apply_type,apply_reason,mon_date,operator,operator_time,remark,check_flag) " +
                "select mon_category_id,type_dtl_id," +
                "apply_type,apply_reason,#{mon_date},operator,now(),remark,'0' " +
                "from ws_eng_assets_monthly_info_dtl where mon_category_id=#{mon_category_id} " +
                "and mon_date=#{mon_date_last} and operator=#{operator}";
        paramsMap.put("isqlStr", sql);
        paramsMap.put("mon_category_id", map.get("mon_category_id"));
        paramsMap.put("mon_date", map.get("mon_date"));
        paramsMap.put("mon_date_last", map.get("mon_date_last"));
        paramsMap.put("operator", map.get("operator"));
        int saveNum = publicMapper.saveItems(paramsMap);
        if (saveNum > 0) {
            return JsonResult.success(saveNum);
        } else {
            return JsonResult.error(400, "新增数据失败");
        }
    }
}
